/**
 * Notes: 表白墙详情页面 (新版API)
 * Ver : WeCollege Server API 1.0.0
 * Date: 2025-01-27
 * Description: 使用新的API服务重构表白墙详情功能
 */

const pageHelper = require('../../../../../helper/page_helper.js');
const BoardBiz = require('../../../biz/board_biz_new.js');
const ProjectBiz = require('../../../biz/project_biz.js');
const PassportBiz = require('../../../../../comm/biz/passport_biz.js');
const { CommentService } = require('../../../../../helper/api_services.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLoad: false,
    id: '',
    
    // 表白墙数据
    board: null,
    
    // 评论数据
    commentList: {
      page: 1,
      size: 20,
      list: [],
      count: 0,
      total: 0
    },
    
    // 评论输入
    commentContent: '',
    replyCommentId: '',
    replyUserId: '',
    replyUserName: '',
    
    // 界面状态
    showCommentInput: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    ProjectBiz.initPage(this);

    if (!pageHelper.getOptions(this, options)) return;

    await this._loadDetail();
    await this._loadComments(true);
  },

  /**
   * 加载表白墙详情
   */
  async _loadDetail() {
    const id = this.data.id;
    if (!id) return;

    try {
      const board = await BoardBiz.view(id); // 使用view增加访问量
      
      if (!board) {
        this.setData({
          isLoad: null
        });
        return;
      }

      this.setData({
        isLoad: true,
        board,
      });

    } catch (err) {
      console.error('加载详情失败:', err);
      this.setData({
        isLoad: null
      });
    }
  },

  /**
   * 加载评论列表
   * @param {boolean} refresh - 是否刷新
   */
  async _loadComments(refresh = false) {
    const id = this.data.id;
    if (!id) return;

    try {
      const currentData = this.data.commentList;
      const page = refresh ? 1 : (currentData.page + 1);
      
      const query = {
        postId: id,
        pageNo: page,
        pageSize: 20,
      };

      const result = await CommentService.queryByPost(query);
      
      // 更新评论数据
      let newList = result.list || [];
      if (!refresh && page > 1) {
        newList = currentData.list.concat(newList);
      }

      this.setData({
        commentList: {
          page: page,
          size: 20,
          list: newList,
          count: result.pages || Math.ceil(newList.length / 20),
          total: result.total || newList.length
        }
      });

    } catch (err) {
      console.error('加载评论失败:', err);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function () {
    await this._loadDetail();
    await this._loadComments(true);
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this._loadComments(false);
  },

  /**
   * 页面跳转
   */
  url: function (e) {
    pageHelper.url(e, this);
  },

  /**
   * 页面滚动事件
   */
  onPageScroll: function (e) {
    // 回页首按钮
    pageHelper.showTopBtn(e, this);
  },

  /**
   * 点赞表白墙
   */
  bindLikeTap: async function (e) {
    if (!await PassportBiz.loginMustCancelWin(this)) return;
    
    const board = this.data.board;
    const isLike = board.IS_LIKE;
    
    try {
      if (isLike) {
        await BoardBiz.dislike(board.BOARD_ID);
      } else {
        await BoardBiz.like(board.BOARD_ID);
      }
      
      // 更新点赞状态
      this.setData({
        'board.IS_LIKE': !isLike,
        'board.BOARD_LIKE_COUNT': board.BOARD_LIKE_COUNT + (isLike ? -1 : 1)
      });
      
    } catch (err) {
      console.error('点赞操作失败:', err);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 显示评论输入框
   */
  bindShowCommentInput: function (e) {
    const { commentId, userId, userName } = pageHelper.dataset(e);
    
    this.setData({
      showCommentInput: true,
      replyCommentId: commentId || '',
      replyUserId: userId || '',
      replyUserName: userName || '',
      commentContent: ''
    });
  },

  /**
   * 隐藏评论输入框
   */
  bindHideCommentInput: function () {
    this.setData({
      showCommentInput: false,
      replyCommentId: '',
      replyUserId: '',
      replyUserName: '',
      commentContent: ''
    });
  },

  /**
   * 评论内容输入
   */
  bindCommentInput: function (e) {
    this.setData({
      commentContent: e.detail.value
    });
  },

  /**
   * 发表评论
   */
  bindSubmitComment: async function () {
    if (!await PassportBiz.loginMustCancelWin(this)) return;
    
    const content = this.data.commentContent.trim();
    if (!content) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    try {
      const commentData = {
        postId: this.data.id,
        content: content,
        lastId: this.data.replyUserId,
        lastCommentId: this.data.replyCommentId
      };

      await CommentService.insert(commentData);
      
      // 隐藏输入框
      this.bindHideCommentInput();
      
      // 刷新评论列表
      await this._loadComments(true);
      
      // 更新表白墙评论数
      const board = this.data.board;
      this.setData({
        'board.BOARD_COMMENT_COUNT': board.BOARD_COMMENT_COUNT + 1
      });
      
      wx.showToast({
        title: '评论成功',
        icon: 'success'
      });
      
    } catch (err) {
      console.error('评论失败:', err);
      wx.showToast({
        title: '评论失败',
        icon: 'none'
      });
    }
  },

  /**
   * 点赞评论
   */
  bindLikeComment: async function (e) {
    if (!await PassportBiz.loginMustCancelWin(this)) return;
    
    const commentId = pageHelper.dataset(e, 'id');
    const isLike = pageHelper.dataset(e, 'like');
    
    try {
      if (isLike) {
        await CommentService.dislike(commentId);
      } else {
        await CommentService.like(commentId);
      }
      
      // 更新评论点赞状态
      this._updateCommentLike(commentId, !isLike);
      
    } catch (err) {
      console.error('评论点赞失败:', err);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 删除评论
   */
  bindDeleteComment: async function (e) {
    const commentId = pageHelper.dataset(e, 'id');
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await CommentService.delete(commentId);
            
            // 刷新评论列表
            await this._loadComments(true);
            
            // 更新表白墙评论数
            const board = this.data.board;
            this.setData({
              'board.BOARD_COMMENT_COUNT': Math.max(0, board.BOARD_COMMENT_COUNT - 1)
            });
            
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
            
          } catch (err) {
            console.error('删除评论失败:', err);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  /**
   * 更新评论点赞状态
   */
  _updateCommentLike: function (commentId, isLike) {
    const list = this.data.commentList.list;
    const index = list.findIndex(item => item.commentId === commentId);
    
    if (index !== -1) {
      const updatePath = `commentList.list[${index}]`;
      this.setData({
        [`${updatePath}.liked`]: isLike,
        [`${updatePath}.likeNum`]: list[index].likeNum + (isLike ? 1 : -1)
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const board = this.data.board;
    if (!board) return {};
    
    return {
      title: board.BOARD_TITLE,
      imageUrl: board.BOARD_PIC && board.BOARD_PIC[0] ? board.BOARD_PIC[0] : ''
    };
  }
});